<template>
  <div class="search">
    <form action="/">
      <van-search
        v-model.trim="value"
        show-action
        background="#21b97a"
        :input-align="algin ? 'center' : 'left'"
        placeholder="请输入小区或地址"
        @search="onSearch"
        @cancel="$router.back()"
        @focus="algin = false"
        @blur="onBlur"
        @input="onSearch"
      />
    </form>
    <van-cell @click="setCommunity(item)" v-for="(item,index) in list" :key="index" :title="item.communityName" />
  </div>
</template>

<script>
import { getCommunity } from '@/api/city.js'
import { Toast } from 'vant'
export default {
  name: 'Search',
  data () {
    return {
      algin: true,
      value: '',
      list: []
    }
  },

  created () {},

  methods: {
    onBlur () {
      if (!this.value) {
        this.algin = true
      }
    },
    onSearch (val) {
      clearInterval(this.timer)
      if (!val) return
      this.timer = setTimeout(async (_) => {
        try {
          const res = await getCommunity(val, this.$store.state.currentCity.id)
          this.list = res.data.body
        } catch (_) {
          Toast.fail('获取失败')
        }
      }, 700)
    },
    setCommunity (item) {
      this.$store.commit('setCom', item)
      this.$router.push('/add')
    }
  }
}
</script>

<style scoped lang="less">
.search {
  .van-search__action {
    color: #fff;
  }
}
</style>
